<?php
class Pageley_Gateway_Database_Condition_SingleSqlDecorator extends Pageley_Gateway_Database_Condition_AbstractSqlDecorator {

	private $query;

	public function __construct($decoratedCondition, $query) {
		parent::__construct($decoratedCondition);
		$this->query = $query;
	}

	protected function createSql() {
		return $this->getColumnExpression() .
			" " . $this->getOperator() .
			" " . $this->getKeyExpression();
	}
	
	public function getColumnExpression() {
	    $type = $this->getQuery()->getType();
        $propertyName = $this->getPropertyName();
        if($propertyName != "id") {
            $attribute = $type->getAttribute($propertyName);
            if($attribute === null) {
                throw new Pageley_Gateway_Database_Exception("No such property '" . $propertyName . "' on type '" . $type->getFullName() . "'.");
            }
        }
        return $this->getQuery()->getAlias($type) .
            ".\"" . $this->getColumnName($propertyName) . "\"";
	}
	
	public function getKeyExpression() {
	    $sqlKey = Pageley_Util_String::addUnderscores(Pageley_Util_String::replace($this->getDecoratedCondition()->getKey(), ".", "_"));
	    return ":" . Pageley_Util_String::addUnderscores($sqlKey);
	}

	public function getValues() {
		$values = $this->getDecoratedCondition()->getValues();
        $sqlValues = new Pageley_Util_ArrayMap();
		$type = $this->getQuery()->getType();
		$propertyName = $this->getPropertyName();
		$converter = null;
		if($propertyName != "id") {
		    $converter = $type->getAttribute($propertyName)->getConverter();
		}
		foreach($values as $key => $value) {
		    if($converter !== null) {
		        $value = $converter->convertIntoFormat($value);
		    }
			$sqlKey = Pageley_Util_String::addUnderscores(Pageley_Util_String::replace($key, ".", "_"));
            $sqlValues->put($sqlKey, $value);
        }
        return $sqlValues;
	}
	
	public function getPropertyName() {
	    return $this->getDecoratedCondition()->getPropertyName();
	}

	public function getQuery() {
		return $this->query;
	}

	protected function getColumnName($propertyName) {
		return $this->query->getColumnName($propertyName);
    }
}